package com.hboxs.asl.controller.app.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.Question;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.service.QuestionService;
import com.hboxs.asl.service.YiYuanTradeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller(value = "appMYiYuanTradeController")
@RequestMapping(value = "/app/m/yiyuanTrade")
public class YiYuanTradeController extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "questionServiceImpl")
    private QuestionService questionService;
    @Resource(name = "yiYuanTradeServiceImpl")
    private YiYuanTradeService yiYuanTradeService;

    /**
     * 生成一元查看答案流水记录
     * @param questionId
     * @return
     */
    @RequestMapping(value = "/yiyuan_pay", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage yiyuanTrade(Long questionId) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Question question = questionService.find(questionId);
            if (question == null) {
                return JsonMessage.error("该易问易答不存在");
            }
            long count = yiYuanTradeService.isPay(member, questionId);
            if (question.getMember() == member || question.getTeacher() == member || count > 0) {
                return JsonMessage.success("已支付");
            }
            String sn = yiYuanTradeService.generateYiYuan(question, member);
            return JsonMessage.success("sn", sn);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}
